import 'dart:async';
import 'dart:ffi';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'
    show BMFCoordinate, BMFEdgeInsets, BMFMapSDK, BMFPoint, BMF_COORD_TYPE;
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmfmap_example/http/http.dart';
import 'package:flutter_bmfmap_example/models/familyinfomodel.dart';
import 'package:flutter_bmfmap_example/tool/tool.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'familycard.dart';

class PositionPage extends StatefulWidget {
  const PositionPage({Key key}) : super(key: key);

  @override
  _PositionPageState createState() => _PositionPageState();
}

class _PositionPageState extends State<PositionPage>
    with SingleTickerProviderStateMixin {
  BMFMapController myMapController;

  List<BMFMarker> markers = [];
  List<BMFCircle> circles = [];

  BMFMapOptions mapOptions = BMFMapOptions(
      compassEnabled: true,
      compassPosition: BMFPoint(50.0, 800.0),
      mapZoomControlPosition: BMFPoint(50.0, 1500.0),
      center: BMFCoordinate(25.0572, 102.74129),
      zoomLevel: 17,
      mapPadding: BMFEdgeInsets(left: 0, top: 0, right: 0, bottom: 0));

  BMFUserLocationDisplayParam displayParam = BMFUserLocationDisplayParam(
      locationViewOffsetX: 0,
      locationViewOffsetY: 0,
      accuracyCircleFillColor: Colors.red,
      accuracyCircleStrokeColor: Colors.blue,
      isAccuracyCircleShow: true,
      locationViewImage: Tool.getportrait(2),
      locationViewHierarchy:
          BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM);

  @override
  void initState() {
    super.initState();

    const timeout = const Duration(seconds: 1);
    
    _timer = Timer.periodic(timeout, (timer) {_updatelocation(); });

  }

  Timer _timer;

  var de = 25.0572;

  _updatelocation(){
    de +=0.0001;
    BMFCoordinate coordinate = BMFCoordinate(de, 102.74129);
    if(markers!=null){
      print('update');
      markers[0].updatePosition(coordinate);
    }
  }

  _getMyhomelocation() {
    BMFCoordinate coordinate = BMFCoordinate(25.0572, 102.74129);
    BMFLocation location = BMFLocation(
        coordinate: coordinate,
        altitude: 0,
        horizontalAccuracy: 5,
        verticalAccuracy: -1.0,
        speed: -1.0,
        course: -1.0);

    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );
    myMapController?.updateLocationData(userLocation);
    setState(() {});
  }

  _getfamily() {
    // var response = await Http.get('/user/detailList');
    // for (int i = 0; i < context.read<FamilyInfomodel>().familylist.length; i++) {
    //   print(i);
    //   // FamilyCard familyCard = new FamilyCard(
    //   //     name: response[i]['personName'], logoid: response[i]['logoId']);
    //   // menulist.add(
    //   //   PopupMenuItem(
    //   //     child: familyCard,
    //   //     value: i,
    //   //   ),
    //   // );

    //   var response2 = await Http.get(
    //       '/watch/getById?id=' + response[i]['watchId'].toString());
    //   print("********************************");
    //   print(response);
    //   print(response2);
    //   print("********************************");
    //   var latitude =
    //       response2['content'].toString().split(';')[4].split(':')[1];
    //   var longitude =
    //       response2['content'].toString().split(';')[3].split(':')[1];
    //   print(latitude);
    //   print(longitude);
    //   BMFMarker marker = BMFMarker(
    //       scaleX: 0.8,
    //       scaleY: 0.8,
    //       position:
    //           BMFCoordinate(double.parse(latitude), double.parse(longitude)),
    //       title: '第一个',
    //       subtitle: 'test',
    //       identifier: 'flutter_marker',
    //       icon: Tool.getportrait(response[i]['logoId']),
    //       enabled: false,
    //       draggable: false);
    //   markers.add(marker);

    //   BMFCircle circle = BMFCircle(
    //       center:
    //           BMFCoordinate(double.parse(latitude), double.parse(longitude)),
    //       radius: response[i]['safeDistance'],
    //       width: 6,
    //       strokeColor: Colors.green,
    //       fillColor: Color.fromRGBO(0, 200, 0, .2),
    //       lineDashType: BMFLineDashType.LineDashTypeSquare);
    //   circles.add(circle);
    //   myMapController?.addCircle(circle);
    // }

    for (int i = 0;
        i < context.read<FamilyInfomodel>().familylist.length;
        i++) {
      var latitude = context
          .read<FamilyInfomodel>()
          .familylist[i]
          .position
          .split(';')[1]
          .split(':')[1];
      var longitude = context
          .read<FamilyInfomodel>()
          .familylist[i]
          .position
          .split(';')[0]
          .split(':')[1];
      print(longitude);
      BMFMarker marker = BMFMarker(
          scaleX: 0.8,
          scaleY: 0.8,
          position:
              BMFCoordinate(double.parse(latitude), double.parse(longitude)),
          title: '第一个',
          subtitle: 'test',
          identifier: 'flutter_marker',
          icon: Tool.getportrait(
              context.read<FamilyInfomodel>().familylist[i].logoId),
          enabled: false,
          draggable: false);
      markers.add(marker);
    }

    myMapController?.addMarkers(markers);
    print('add');
    // markers[1].updatePosition();
  }

  @override
  void dispose() {
    print('dispose');
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    
    return Stack(
      children: [
        Container(
          width: width,
          height: height,
          child: BMFMapWidget(
            onBMFMapCreated: (controller) {
              myMapController = controller;
              //以下设置家庭位置
              controller.showUserLocation(true);
              _getMyhomelocation();
              _getfamily();
              myMapController.updateLocationViewWithParam(displayParam);
            },
            mapOptions: mapOptions,
          ),
        ),
        // _buildsearchbar(),
        SafeArea(
          child: Stack(
            children: [
              _buildsearchbar(),
            ],
          ),
        ),
        SafeArea(
          child: Stack(
            children: [
              Positioned(
                right: 16,
                bottom: 160,
                child: GestureDetector(
                  onTap: () {
                    myMapController?.setCenterCoordinate(
                        BMFCoordinate(25.0572, 102.74129), true,
                        animateDurationMs: 500);
                  },
                  child: SvgPicture.asset(
                    "assets/images/icons/svg/backlocation.svg",
                    color: Colors.black54,
                    width: 32,
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  _setCenterfamily(String position) {
    print(position);

    var latitude = double.parse(position.split(';')[1].split(':')[1]);
    var longitude = double.parse(position.split(';')[0].split(':')[1]);

    myMapController?.setCenterCoordinate(
        BMFCoordinate(latitude, longitude), true,
        animateDurationMs: 500);
  }

  _buildsearchbar() {
    return Positioned(
      // top: 0,
      child: Container(
        margin: EdgeInsets.only(top: 16, left: 28, right: 28),
        height: 56,
        child: Row(
          children: [
            SizedBox(
              width: 8,
            ),
            Container(
              width: 44,
              height: 44,
              decoration: new BoxDecoration(
                color: Colors.white,
                borderRadius: new BorderRadius.circular((12.0)),
                boxShadow: [
                  BoxShadow(
                      color: Colors.black12,
                      offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                      blurRadius: 5.0, //阴影模糊程度
                      spreadRadius: 0.1 //阴影扩散程度
                      ),
                ],
              ),
              child: Center(
                child: new PopupMenuButton(
                  icon: Icon(Icons.list),
                  onSelected: (var value) {
                    print(value);
                    _setCenterfamily(context
                        .read<FamilyInfomodel>()
                        .familylist[value]
                        .position);
                    setState(() {
                      //  _bodyStr = value;
                    });
                  },
                  // itemBuilder: (BuildContext context) {
                  //   return menulist;
                  // },

                  itemBuilder: (BuildContext context) {
                    // return context.read<FamilyInfomodel>().familylist.map((e) {
                    //   FamilyCard familyCard =
                    //       new FamilyCard(name: e.personName, logoid: e.logoId);
                    //   return PopupMenuItem(
                    //     child: familyCard,
                    //     value: e.id,
                    //   );
                    // }).toList();
                    List<PopupMenuItem<int>> menulist = [];
                    for (int i = 0;
                        i < context.read<FamilyInfomodel>().familylist.length;
                        i++) {
                      FamilyCard familyCard = new FamilyCard(
                          name: context
                              .read<FamilyInfomodel>()
                              .familylist[i]
                              .personName,
                          logoid: context
                              .read<FamilyInfomodel>()
                              .familylist[i]
                              .logoId);
                      menulist.add(
                        PopupMenuItem(
                          child: familyCard,
                          value: i,
                        ),
                      );
                    }

                    return menulist;
                  },
                ),
              ),
            ),
            Spacer(),
            GestureDetector(
              onTap: () {
                context.read<FamilyInfomodel>().updatelocation();
              },
              child: Container(
                width: 44,
                height: 44,
                decoration: new BoxDecoration(
                  color: Colors.white,
                  borderRadius: new BorderRadius.circular((12.0)),
                  boxShadow: [
                    BoxShadow(
                        color: Colors.black12,
                        offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                        blurRadius: 5.0, //阴影模糊程度
                        spreadRadius: 0.1 //阴影扩散程度
                        ),
                  ],
                ),
                child: Center(
                  child: SvgPicture.asset(
                    "assets/images/icons/svg/消息.svg",
                    color: Colors.black54,
                    width: 28,
                  ),
                ),
              ),
            ),
            SizedBox(
              width: 8,
            ),
          ],
        ),
      ),
    );
  }
}
